#!/usr/bin/python


from saas.const import *
from saas.misc import *
from saas.db import *
from saas.log import *
from saas.conf import *
from saas.listener import *
import sys
import time
import os


class SAAS_Instance:
	conf_path = '/etc/saasd.conf'
	db        = None
	conf      = None
inst = SAAS_Instance()


## here we go.
log_open( '/var/log/saasd.log' )
logm( LOG_INFO , 'SAAS server starting...' )


## first thing to do is to parse the config file, and output the data
## that has been loaded in.
logm( LOG_DEBUG , 'Opening and parsing config file...' )
inst.conf = conf()
inst.conf.parse( inst.conf_path )
inst.conf.dump()
logm( LOG_DEBUG , 'Successfully opened and parsed config file.' )


## do some sanity checks before going forward...
if conf.use_ipv4 == 0 and conf.use_ipv6 == 0:
	logm( LOG_ERROR , 'Neither IPv4 nor IPv6 have been enabled. You must enable at least one.' )
	sys.exit( 1 )


## open the SQLite database.
logm( LOG_DEBUG , 'Attempting to open database...' )
inst.db = db()
inst.db.mount( inst.conf.db_path )
logm( LOG_DEBUG , 'Successfully opened database.' )



## daemonise!
logm( LOG_DEBUG , 'Attempting to daemonise...' )
pid = os.fork()
if (pid == 0):
	os.setsid()
	pid = os.fork()
	if (pid == 0):
		## awesome, we're a daemon now.
		logm( LOG_DEBUG , 'Successfully daemonised.' );
	else:
		os._exit( 0 )
else:
	os._exit( 0 )


## start the listener and block there until the server
## has been signalled to shut down.
listen( inst )


## unmount the SQLite db
inst.db.umount()

log_close()

## and exit successfully. hooray!
sys.exit( 0 )


